#include <atomic>
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>

// 任务类型
enum class TaskType { INTERACTIVE,
    BATCH,
    REALTIME };

// 模拟任务
struct Task {
    int id;
    TaskType type;
    int burst_time; // 模拟执行时间 (ms)
    int priority; // 优先级（动态变化）
    int cpu_affinity; // -1 表示未绑定，>=0 表示绑定到某个CPU

    // 比较函数，priority 越高越优先
    bool operator<(const Task& other) const
    {
        return priority < other.priority;
    }
};

// 全局队列 (未绑定 CPU 的任务)
std::priority_queue<Task> global_queue;
std::mutex global_mutex;
std::condition_variable cv;
std::atomic<bool> running(true);

int cpu_count = 2; // 模拟双核
// cpu_queues.resize(cpu_count);
// cpu_mutexes.resize(cpu_count);
// 每个 CPU 单独的队列 (绑定任务)
std::vector<std::priority_queue<Task>> cpu_queues(cpu_count);
std::vector<std::mutex> cpu_mutexes(cpu_count);

// 调度器线程
void scheduler(int cpu_id)
{
    while (running) {
        Task current;
        bool has_task = false;

        // 1. 先看是否有绑定到该 CPU 的任务
        {
            std::lock_guard<std::mutex> lock(cpu_mutexes[cpu_id]);
            if (!cpu_queues[cpu_id].empty()) {
                current = cpu_queues[cpu_id].top();
                cpu_queues[cpu_id].pop();
                has_task = true;
            }
        }

        // 2. 如果没有绑定任务，再从全局队列里取
        if (!has_task) {
            std::unique_lock<std::mutex> lock(global_mutex);
            if (global_queue.empty()) {
                cv.wait_for(lock, std::chrono::milliseconds(100));
                continue;
            }
            current = global_queue.top();
            global_queue.pop();
            has_task = true;
        }

        if (has_task) {
            // 模拟时间片执行
            int time_slice = 50;
            int exec_time = std::min(time_slice, current.burst_time);

            std::cout << "[CPU " << cpu_id << "] Running task " << current.id
                      << " (priority=" << current.priority
                      << ", affinity=" << current.cpu_affinity
                      << ") for " << exec_time << "ms\n";

            std::this_thread::sleep_for(std::chrono::milliseconds(exec_time));
            current.burst_time -= exec_time;

            if (current.burst_time > 0) {
                // 动态调节优先级 (等待越久，优先级越高)
                current.priority += 1;
                if (current.cpu_affinity == -1) {
                    std::lock_guard<std::mutex> lock(global_mutex);
                    global_queue.push(current);
                } else {
                    std::lock_guard<std::mutex> lock(cpu_mutexes[current.cpu_affinity]);
                    cpu_queues[current.cpu_affinity].push(current);
                }
                cv.notify_all();
            }
        }
    }
}

// 提交任务
void submit_tasks()
{
    std::vector<Task> tasks = {
        { 1, TaskType::REALTIME, 100, 50, -1 }, // 实时任务，不绑定
        { 2, TaskType::INTERACTIVE, 150, 15, 0 }, // 绑定到 CPU0
        { 3, TaskType::BATCH, 300, 5, -1 }, // 批处理任务，不绑定
        { 4, TaskType::BATCH, 200, 5, 1 }, // 绑定到 CPU1
        { 5, TaskType::INTERACTIVE, 120, 10, -1 } // 不绑定
    };

    for (auto& t : tasks) {
        if (t.cpu_affinity == -1) {
            std::lock_guard<std::mutex> lock(global_mutex);
            global_queue.push(t);
        } else {
            std::lock_guard<std::mutex> lock(cpu_mutexes[t.cpu_affinity]);
            cpu_queues[t.cpu_affinity].push(t);
        }
    }
    cv.notify_all();
}

int main()
{
    // 启动调度线程
    std::vector<std::thread> cpus;
    for (int i = 0; i < cpu_count; i++) {
        cpus.emplace_back(scheduler, i);
    }

    // 提交任务
    submit_tasks();

    // 运行 2 秒后停止
    std::this_thread::sleep_for(std::chrono::seconds(2));
    running = false;
    cv.notify_all();

    for (auto& t : cpus) {
        t.join();
    }

    return 0;
}
